package yxk.task.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import yxk.utils.BosUtil;
import yxk.utils.DateUtil;
import yxk.utils.HttpRequestUtil;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 请求工具类
 */
public class RequesUtil {
    private DynamicObject HUILIANYI;
    private DynamicObject  FEISHUDAKA;
    private DynamicObject HAIKAN;
    private static final Log LOG = LogFactory.getLog(RequesUtil.class);

    /**
     * 获取汇联易出差申请单
     * @return
     */
    public List<JSONArray> getHUYClockDataRequest(){
        if(HUILIANYI == null){
            HUILIANYI= BosUtil.getConfigUration("HUILIANYI");
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String url = HUILIANYI.getString("nwg5_url");
        Calendar instance = Calendar.getInstance();

        Date date = DateUtil.MonthAdd(instance.getTime(),Calendar.MONTH ,-3);
        Date dateEnd = DateUtil.MonthAdd(instance.getTime(),Calendar.YEAR ,+1);
        String toKen = getHLYToKen();
        List<JSONArray> list=new ArrayList<>();
        int respLength=0;
        int i=1;
        do {
            StringBuffer paramUrl=new StringBuffer();
            paramUrl.append("startDate="+sdf.format(date));
            paramUrl.append("&");
            paramUrl.append("endDate=");
            paramUrl.append(sdf.format(dateEnd));
            paramUrl.append("&");
            paramUrl.append("withApplicationParticipant=true&");
            paramUrl.append("withItineraryMap=true&");
            paramUrl.append("status=1003,1009,1011,1012&");
            paramUrl.append("size=100&");
            paramUrl.append("page=");
            paramUrl.append(i);
            LOG.info("RequesUtil.getHUYClockDataRequest.paramUrl:{}",paramUrl);
            Map mapHeader=new HashMap<>();
            mapHeader.put("Authorization","Bearer " + toKen);
            String respone = HttpRequestUtil.sendJsonGet(url,paramUrl.toString(), mapHeader);
            LOG.info("RequesUtil.getHUYClockDataRequest.respone:{}",respone);
            if(respone != null) {
                JSONArray array = JSONObject.parseArray(respone);
                list.add(array);
                respLength = array.size();
            }
            ++i;
        }while (respLength == 100);
        return list;
    }

    /**
     * 汇联易获取token
     */
    public String getHLYToKen() {
        if(HUILIANYI == null){
            HUILIANYI= BosUtil.getConfigUration("HUILIANYI");
        }
        String tokenUrl = HUILIANYI.getString("nwg5_tokenurl");
        String clientId = HUILIANYI.getString("nwg5_user");
        String securet = HUILIANYI.getString("nwg5_password");
        int MAX_TIME_OUT = 1000 * 120;
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(MAX_TIME_OUT);
        httpRequestFactory.setConnectTimeout(MAX_TIME_OUT);
        httpRequestFactory.setReadTimeout(MAX_TIME_OUT);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(httpRequestFactory);

        HttpHeaders httpHeaders = new HttpHeaders();
        String authStr = clientId.concat(":").concat(securet);
        String authStrEnc = new String(Base64.encodeBase64(authStr.getBytes()));
        httpHeaders.set("Authorization", "Basic ".concat(authStrEnc));

        MultiValueMap<String, String> formData = new LinkedMultiValueMap();
        formData.add("grant_type", "client_credentials");
        formData.add("scope", "write");
        LOG.info("RequesUtil.getHLYToKen.formData:{},httpHeaders:{}",formData,httpHeaders);
        HttpEntity httpEntity = new HttpEntity(formData, httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(tokenUrl, HttpMethod.POST, httpEntity, String.class);

        String results = exchange.getBody();
        LOG.info("RequesUtil.getHLYToKen.results:{},exchange:{}",results,exchange);
       try {
           Map<String, Object> datas = JSONObject.parseObject(results);
           String accessToken = (String) datas.get("access_token");
           return accessToken;
       }catch (Exception e){
           LOG.error("RequesUtil.getHLYToKen.e{}",e);
           return null;
       }
    }

    /**
     *   海康打卡数据同步
     * @param startStr  开始时间
     * @param endStr    结束时间
     * @param receiveStartTime    入库开始时间
     * @param receiveEndTime    入库结束时间
     * @return
     */
    public List<JSONArray> getHKClockRequest(String startStr,String endStr,String receiveStartTime,String receiveEndTime){
        List<JSONArray> list=new ArrayList<>();
        if(HAIKAN==null){
            HAIKAN = BosUtil.getConfigUration("HAIKAN");
        }
        String hkToKen = getHKToKen();
        LOG.info("RequesUtil.getHKClockRequest.hkToKen{}",hkToKen);
        if(hkToKen == null){
            return null;
        }
        LOG.info("RequesUtil.getHKClockRequest.HAIKAN{}",HAIKAN);
        String url = HAIKAN.getString("nwg5_url");
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("startTime",startStr);
        jsonObject.put("endTime",endStr);
        jsonObject.put("receiveStartTime",receiveStartTime);
        jsonObject.put("receiveEndTime",receiveEndTime);
        jsonObject.put("pageSize",1000);
        int i=1;
        int total;
        do {
            total=0;
            jsonObject.put("pageNo",i);
            LOG.info("RequesUtil.getHKClockRequest.jsonObject{}",jsonObject);
            Map mapHeader=new HashMap<>();
            mapHeader.put("access_token",hkToKen);
            try {
                String results = HttpRequestUtil.getPostResult(url, mapHeader, jsonObject.toString(), "application/json; charset=UTF-8");
                LOG.info("RequesUtil.getHKClockRequest.results{}",results);
                if(results != null){
                    JSONObject datas = JSONObject.parseObject(results);
                    Object code = datas.get("code");
                    if(code.equals(0) || "0".equals(code.toString())){
                            JSONObject data =  datas.getJSONObject("data");
                            JSONArray jsonData = data.getJSONArray("list");
                            total = jsonData.size();
                            list.add(jsonData);
                    }

                }
            }catch (Exception e){
                LOG.error("RequesUtil.getHKClockRequest.e{}",e);
                break;
            }
            ++i;
        }while (total != 0 && total == 1000);
        return list;
    }


    /**
     *获取海康token
     * @return
     */
    public String getHKToKen(){
        String ARTEMIS_PATH = "/artemis";
        if(HAIKAN==null){
            HAIKAN = BosUtil.getConfigUration("HAIKAN");
        }
        String tokenurl = HAIKAN.getString("nwg5_tokenurl");
        String user = HAIKAN.getString("nwg5_user");
        String password = HAIKAN.getString("nwg5_password");
        String nwg5Secreturl = HAIKAN.getString("nwg5_secreturl");
        LOG.info("RequesUtil.getHKToKen.tokenurl{},user{},password{}",tokenurl,user,password);
        try {
            ArtemisConfig config = new ArtemisConfig();
            config.setHost(nwg5Secreturl); // 代理API网关nginx服务器ip端口
            config.setAppKey(user);  // 秘钥appkey
            config.setAppSecret(password);// 秘钥appSecret
            String getCamsApi = ARTEMIS_PATH + "/api/v1/oauth/token";
            Map<String, String> path = new HashMap<String, String>(2) {
                {
                    put("https://", getCamsApi);
                }
            };
            LOG.info("RequesUtil.getHKToKen.config:{},path:{}",config,path);
            String results = ArtemisHttpUtil.doPostStringArtemis(config, path, null, null, null, "application/json");
            LOG.info("RequesUtil.getHKToKen.results{}",results);
            Map<String, Object> datas = JSONArray.parseObject(results);
            Object code = datas.get("code");
            if(code !=null && (code.equals(0) || "0".equals(code.toString()))){
                Map<String,Object> data = (Map<String,Object>) datas.get("data");
                String token = data.get("access_token").toString();
                LOG.info("RequesUtil.getHKToKen.token{}",token);
                return token;
            }
        }catch (Exception e){
            LOG.error("RequesUtil.getHKToKen.e{}",e);
        }
        return null;
    }






    /**
     *
     * @param userIds 用户工号集合
     * @return 根据工号获取飞书前一天的打卡记录
     */
    public List<Map<String,Object>> getFSClockRequest(List<List<String>> userIds,String startDate,String endDate){
        if(FEISHUDAKA == null){
            FEISHUDAKA=BosUtil.getConfigUration("FEISHUDAKA");
        }
        List<Map<String,Object>> list=new ArrayList<>();
        String nwg5_url = FEISHUDAKA.getString("nwg5_url");
        LOG.info("PunchcardDataUtil.getFSClockRequest.nwg5_url:{}",nwg5_url);

        String fsToken = getFSToken();//获取飞书的token
        LOG.info("PunchcardDataUtil.getFSClockRequest.startDate:{},endDate:{},fsToken:{}",startDate,fsToken);
        if("".equals(fsToken) || fsToken == null){
            return null;
        }
        JSONObject param=new JSONObject();
        //对于无效人员是否返回; true:返回无效人员；false:返回错误
        param.put("ignore_invalid_users","true");

        param.put("check_date_from",startDate);//开始时间
        param.put("check_date_to",endDate);//结束时间
        LOG.info("PunchcardDataUtil.getFSClockRequest.param:{}",param);
        //每五十条数据查询一次打卡记录
        LOG.info("PunchcardDataUtil.getFSClockRequest.userIds:{}",userIds);
        for (List<String> userId : userIds) {
            LOG.info("PunchcardDataUtil.getFSClockRequest.userId:{}",userId);
            param.put("user_ids",userId);
            try {
                LOG.info("PunchcardDataUtil.getFSClockRequest.userparam:{}",param);
                Map mapHeader=new HashMap<>();
                mapHeader.put("Authorization","Bearer "+fsToken);
                String results = HttpRequestUtil.getPostResult(nwg5_url+"?employee_type=employee_id",mapHeader,param.toString(),"application/json;charset=utf-8");
                LOG.error("RequesUtil.getFSClockRequest.Requesterror.results:{}",results);
                Map<String,Object> datas = JSONObject.parseObject(results);
                Object code = datas.get("code");
                if(code !=null && code.equals(0)){
                    list.add(datas);
                }
            }catch (Exception e){
                e.printStackTrace();
                LOG.error("RequesUtil.getFSClockRequest.Requesterror.e:{}",e);
            }
        }
        LOG.info("PunchcardDataUtil.getFSClockRequest.list:{}",list);
        return list;
    }

    /**
     * 飞书token获取地址
     * */
    public String getFSToken() {
        String result="";
        if(FEISHUDAKA == null){
            FEISHUDAKA=BosUtil.getConfigUration("FEISHUDAKA");
        }
        LOG.info("PunchcardDataUtil.getFSToken.config:{}",FEISHUDAKA);
        String nwg5Tokenurl = FEISHUDAKA.getString("nwg5_tokenurl");
        JSONObject param=new JSONObject();
        param.put("app_id",FEISHUDAKA.getString("nwg5_user"));
        param.put("app_secret",FEISHUDAKA.getString("nwg5_password"));
        LOG.info("PunchcardDataUtil.getFSToken.param:{}",param);
        try{
            String results = HttpRequestUtil.getPostResult(nwg5Tokenurl,null,param.toString(),"application/json;charset=utf-8");
            LOG.info("PunchcardDataUtil.getFSToken.result:{}",results);

            Map<String,Object> datas =  JSONObject.parseObject(results);
            Object code = datas.get("code");
            if(code !=null && code.equals(0)){
                result = datas.get("tenant_access_token").toString();
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
            LOG.error("RequesUtil.getFSToken.e:{}",e);
        }
        return result;
    }

}